package com.msmall.community.vote.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.msmall.base.dao.hibernate.BaseDaoHibernate;
import com.msmall.base.util.ConstantDB;
import com.msmall.community.vote.dao.VoteDao;
import com.msmall.community.vote.model.Vote;

public class VoteDaoHibernate extends BaseDaoHibernate<Vote,Long> implements VoteDao{

	public VoteDaoHibernate(){
		super(Vote.class);
	}
	/**
	 * 获得voter对 voted的最近一次投票信息，可以用来防止刷票
	 * @param voter
	 * @param voted
	 * @throws Exception 
	 */
	public Vote loadLastVote(Long voter, Long voted, Integer module) throws Exception{
		try{
			String queryString = "from Vote where module=" + module +" and voter="+voter+" and voted="+voted+" order by createTime desc limit 1";
			List list = super.getHibernateTemplate().find(queryString);
			if(list!= null && list.size() > 0)
				return (Vote) list.get(0);
			return null;
		}catch(Exception e){
			throw e;
		}
	}
	/**
	 * 获得旅游达人的投票前10名 ,只有被投票人ID，和受到的投票数量
	 */
	public List loadTravelVote() throws Exception{
		Session session =null;
		try{
			session = getSession();
			String queryString = "select v.voted, count(v.voted), u.avatar from Vote v, UserInfo u where v.voted=u.userid and v.module=" + ConstantDB.VOTE_MODULE_TRAVEL +" and v.types=" + ConstantDB.VOTE_TYPES_POSITIVE+ " group by v.voted order by count(v.voted) desc";
			Query query = session.createQuery(queryString);
	 		query.setFirstResult(0)
	 			.setMaxResults(10);
	 		List list = query.list();
			return list;
		}catch(Exception e){
			throw e;
		}finally{
			releaseSession(session);
		}
	}
	/**
	 * 查看用户在某个模块受到的所有投票数量
	 */
	public Integer loadTotalVote(Long voted, Integer module, Integer types) throws Exception{
		try{
			String queryString = "select count(voted) from Vote where module=" + module +" and types=" + types+ " and voted=" +voted+" group by voted";
			List list = super.getHibernateTemplate().find(queryString);
			if(list !=null && list.size() > 0){
				Long count = (Long) list.get(0);
				return Integer.valueOf(String.valueOf(count));
			}
			return 0;
		}catch(Exception e){
			throw e;
		}
	}
}
